<template>
	<div class="dataFlowViewer">
		<a-tabs v-model:activeKey="config.currentTab" :tab-position="left" animated>
			<a-tab-pane key="input" tab="input">
				<h-table
					:paged="false"
					ref="inputTableRef"
					:data="config.inputData"
					:columns="config.inputColumns"
					height="200px"
				>
				</h-table>
			</a-tab-pane>
			<a-tab-pane key="output" tab="output">
				<h-table
					:paged="false"
					ref="outputTableRef"
					:data="config.outputData"
					:columns="config.outputColumns"
					height="200px"
				>
				</h-table>
			</a-tab-pane>
		</a-tabs>
	</div>
</template>

<script setup>
	import { jsonChildToString } from '@/utils'

	const props = defineProps(['dataFlow'])

	const config = ref({
		currentTab: 'input',
		inputColumns: [],
		inputData: [],
		outputColumns: [],
		outputData: []
	})

	const inputTableRef = ref()
	const outputTableRef = ref()

	onMounted(() => {
		setDataFlowInput()
		setDataFlowOutput()
	})

	watch(
		() => props.dataFlow?.input,
		(n, o) => {
			setDataFlowInput()
		},

		{ deep: true }
	)

	watch(
		() => props.dataFlow?.output,
		(n, o) => {
			setDataFlowOutput()
		},

		{ deep: true }
	)

	const setDataFlowOutput = () => {
		if (!props.dataFlow?.output) {
			return
		}
		let columns = buildColumns(props.dataFlow?.output)
		config.value.outputColumns = columns
		config.value.outputData = jsonChildToString(props.dataFlow?.output)
	}

	const setDataFlowInput = () => {
		if (!props.dataFlow?.input) {
			return
		}
		let columns = buildColumns(props.dataFlow?.input)
		config.value.inputColumns = columns
		config.value.inputData = jsonChildToString(props.dataFlow?.input)
	}

	const buildColumns = (data) => {
		if (!data) {
			return []
		}
		const columns = []
		for (const dt of data) {
			for (const fieldInfo in dt) {
				if (!columnsContains(fieldInfo, columns)) {
					columns.push({
						title: fieldInfo,
						dataIndex: fieldInfo,
						key: fieldInfo,
						ellipsis: true
					})
				}
			}
		}
		return columns
	}
	const columnsContains = (fieldName, columns) => {
		let find = false
		if (fieldName == '_key') {
			return true
		}
		for (const column of columns) {
			if (column.key == fieldName) {
				find = true
				break
			}
		}
		return find
	}
</script>

<style scoped lang="less">
	.dataFlowViewer {
		width: 500px;
		height: 200px;
		background-color: white;
	}
</style>
